package com.hpsk.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hpsk.thread.ThreadLocalTokenId;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 删除标志
     */
    @Value("${mybatis-plus.global-config.db-config.logic-delete-field}")
    private String logicDeleteField;
    /**
     * 删除标志值
     */
    @Value("${mybatis-plus.global-config.db-config.logic-not-delete-value}")
    private String logicNotDeleteValue;

    /**
     * 创建人
     */
    private static final String CREATE_USER = "createUser";

    /**
     * 创建时间
     */
    private static final String CREATE_TIME = "createTime";

    /**
     * 更新人
     */
    private static final String UPDATE_USER = "updateUser";

    /**
     * 更新时间
     */
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        setFieldValByName("deleteFlag", logicNotDeleteValue, metaObject);
        setFieldValByName(UPDATE_USER, getUserId(), metaObject);
        setFieldValByName(CREATE_USER,getUserId(), metaObject);
        setFieldValByName(CREATE_TIME, LocalDateTime.now(), metaObject);
//        this.strictInsertFill(metaObject, logicDeleteField, String.class, logicNotDeleteValue);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName(UPDATE_USER, getUserId(), metaObject);
        setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
    }

    /**
     * 获取用户id
     */
    private String getUserId() {
        try {
            String userId = ThreadLocalTokenId.get();
            if (ObjectUtil.isNotEmpty(userId)) {
                return userId;
            } else {
                return "-1";
            }
        } catch (Exception e) {
            return "-1";
        }

    }
}
